package com.hmdp.interceptor;

import cn.hutool.db.nosql.redis.RedisDS;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 第一层拦拦截器，用于刷新tokeng过期时间，不管是【已经登录过的用户】访问不需要登录的接口，还是需要登录的接口，都刷新token的过期时间
 */
@Component
public class RefreshTokenExpireInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("authorization");
        if (token == null || token == "") {
            return true;
        }

        String key = "token:" + token;
        String jsonStr = redisTemplate.opsForValue().get(key);
        if (jsonStr == null || jsonStr == "") {
            return true;
        }
        UserDTO userDTO = JSONUtil.toBean(jsonStr, UserDTO.class);
        UserHolder.saveUser(userDTO);
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
